<?php

class  SCup_session
{

    var $_session_name = '';
    var $_session_id ='';  
    var $_db             = NULL;

    var $_session_table  = '';
    var $_max_life_time  = 1440; // SESSION 过期时间
    var $_time  = 0;

    var $_session_expiry = '';
    var $_session_md5    = '';
	
    var $_session_cookie_path   = '/';
    var $_session_cookie_domain = '';
    var $_session_cookie_secure = false;	
    var $_ip   = '';
 

    function __construct($_session_table, $_session_name = 'SCUP_SESSION', $_session_id = '')
    {
        $this->SCup_session($_session_table, $_session_name, $_session_id);
    }

   function SCup_session($session_table,$session_name = 'SCUP_SESSION', $session_id = '')
    {
      
        $this->_max_life_time = SESSION_MAX_LIFE_TIME;
        $this->_session_cookie_path = COOKIE_PATH;
        $this->_session_cookie_domain = COOKIE_DOMAIN;
		$this->_db = &get_db();
        $this->_ip = get_ip();		
        $this->_session_cookie_secure = false;
        $this->_time = time();

        $this->_session_name       = $session_name;
        $this->_session_table      = $session_table;
		
		$cookie_var = get_cookie($this->_session_name);

        /*处理session id*/
        if ($session_id == '' && !empty($cookie_var))
        {
            $this->_session_id = $cookie_var;
        }
        else
        {
            $this->_session_id = $session_id;
        }

        if ($this->_session_id)
        {
            $tmp_session_id = substr($this->_session_id, 0, 32);
			
            if ($this->get_session_key($tmp_session_id) == substr($this->_session_id, 32))
            {
                $this->_session_id = $tmp_session_id;
            }
            else
            {
                $this->_session_id = '';
            }
        }

        if (!$this->_session_id)
        {
            $this->get_session_id();
            set_cookie($this->_session_name, $this->_session_id . $this->get_session_key($this->_session_id), 0,'', '','');
           // set_cookie($this->_session_name, $this->_session_id . $this->get_session_key($this->_session_id), 0,$this->_session_cookie_path, $this->_session_cookie_domain, $this->_session_cookie_secure);
        }
		else
		{
		
		    $this->load_session();
		
		}
		
		register_shutdown_function(array(&$this, 'close_session'));

    }


    function get_session_id()
    {
        $this->_session_id = md5(uniqid(mt_rand(), true));
        return $this->insert_session();
    }

    function get_session_key($session_id)
    {
        $ip = substr($this->_ip, 0, strrpos($this->_ip, '.'));		
        return sprintf('%08x', crc32(!empty($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] . ROOT_PATH . $ip . $session_id : ROOT_PATH . $ip . $session_id));		
    }


    function load_session()
    {
        $session = $this->_db->get_one("SELECT  expiry, user_id, ip, data, is_overflow FROM " . $this->_session_table . " WHERE sesskey = '" . $this->_session_id . "'");
				
        if (empty($session))
        {	
            $this->insert_session();
			$this->_session_expiry = 0;
            $this->_session_md5    = '40cd750bba9870f18aada2478b24840a';
        }
        else
        {    
		    if($session['is_overflow']!=0)
			{
                $this->destroy_session();
			}
		
            if (!empty($session['user_id']) && (($this->_time - $session['expiry']) <= $this->_max_life_time))
            {
			 
                $this->_session_expiry = $session['expiry'];
                $this->_session_md5    = md5($session['data']);
											
                $GLOBALS['SCup']->SCup_user_msg['data']  = unserialize($session['data']);
		        if(!isset($GLOBALS['SCup']->SCup_user_msg['data']['view_start_or_stop']))
		        {
		         $GLOBALS['SCup']->SCup_user_msg['data']['view_start_or_stop']=0;
		        }									
                $GLOBALS['SCup']->SCup_user_msg['user_id']  = $session['user_id'];
				
				$GLOBALS['SCup']->SCup_user_checking = true;//判断用户是否登入
				
            }
            else
            {		

			    $GLOBALS['SCup']->SCup_user_msg['data']  = array();
                $GLOBALS['SCup']->SCup_user_msg['user_id']  = 0;
                $this->_session_expiry = 0;
                $this->_session_md5    = '40cd750bba9870f18aada2478b24840a';				
            }
			
        }
    }

    function insert_session()
    {
        return $this->_db->query('INSERT INTO ' . $this->_session_table . " (sesskey, expiry, ip, data) VALUES ('" . $this->_session_id . "', '". $this->_time ."', '". $this->_ip ."', 'a:0:{}')");       
		
    }
	
    function close_session()
    {
        $this->update_session();

        if ((time() % 2) == 0)
        {
            return $this->_db->query('DELETE FROM ' . $this->_session_table . ' WHERE expiry < ' . ($this->_time - $this->_max_life_time));
        }

        return true;        		
    }

    function destroy_session()
    {
	
        set_cookie($this->_session_name, $this->_session_id, 1, $this->_session_cookie_path, $this->_session_cookie_domain, $this->_session_cookie_secure);
		
        return $this->_db->query('DELETE FROM ' . $this->_session_table . " WHERE sesskey = '" . $this->_session_id . "' LIMIT 1");
		
    }
	

    function update_session()
    {        

        $data        = serialize($GLOBALS['SCup']->SCup_user_msg['data']);
		

		$user_id     = $GLOBALS['SCup']->SCup_user_msg['user_id'];	
		if(empty($user_id))
		{
		$user_id = '0';
		}	
        $this->_time = time();
		//以下表示过1秒钟更改一次数据
        if ($this->_session_md5 == md5($data) && $this->_time < $this->_session_expiry + 1)
        {
            return true;
        }
		
        $data = addslashes($data);

		if (isset($data{40000}))
        {
            $this->_db->query("REPLACE INTO `{$this->_session_table}` SET sesskey = '{$this->_session_id}', expiry={$this->_time}, user_id = '{$user_id}', ip = '{$this->_ip}', data='{$data}'");
            $data = '';
			$user_id = '0';
        }

        return $this->_db->query('UPDATE ' . $this->_session_table . " SET expiry = '" . $this->_time . "', ip = '" . $this->_ip . "', user_id = '" . $user_id . "', data = '{$data}' WHERE sesskey = '" . $this->_session_id . "' LIMIT 1");
	
	}

    function get_users_count()
    {
	    $num = $this->_db->get_one("SELECT  count(*) as totalnum FROM " . $this->_session_table .' ');
        return $num['totalnum'] ;
    }	

}



?>